package com.calligraphy.apigateway.filter;

import com.alibaba.fastjson.JSON;
import com.calligraphy.apigateway.utils.CookieUtil;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.PRE_DECORATION_FILTER_ORDER;
import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.PRE_TYPE;

/**
 * @Author hy
 * @Date 2019/1/3 16:51
 **/
@Component
public class AuthFilter extends ZuulFilter {

    private static final String TOKEN_COOKIE = "token";

    @Autowired
    private RestTemplate restTemplate;

    @Override
    public String filterType() {
        return PRE_TYPE;
    }

    @Override
    public int filterOrder() {
        return PRE_DECORATION_FILTER_ORDER - 1;
    }

    @Override
    public boolean shouldFilter() {
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();
        String requestUrl = request.getRequestURL().toString();
        // 请求URL内不包含此路径则需要经过该过滤器，即执行run()
        return !requestUrl.contains("/route_u/user/logout") && !requestUrl.contains("/route_u/user/login");
    }

    @Override
    public Object run() {
        RequestContext requestContext = RequestContext.getCurrentContext();
        HttpServletRequest req = requestContext.getRequest();
        HttpServletResponse response = requestContext.getResponse();
        Cookie cookie = CookieUtil.get(req,TOKEN_COOKIE);
        if(cookie != null && !StringUtils.isEmpty(cookie.getValue())){
            String token = cookie.getValue();
            MultiValueMap<String, String> map= new LinkedMultiValueMap<>();
            map.add("token",token);
            String result =  restTemplate.postForObject("http://USER/user/auth",map,String.class);
            if("0".equals(result)){
                requestContext.addZuulResponseHeader("token",token);
                requestContext.setSendZuulResponse(true);
                requestContext.setResponseStatusCode(HttpStatus.OK.value());
            }
        }else {
            response.setHeader("Content-Type", "application/json;charset=UTF-8");
            requestContext.setSendZuulResponse(false);
            requestContext.setResponseStatusCode(400);
            Map<String,String> responseMap=new HashMap<>(10);
            responseMap.put("errorCode", HttpStatus.BAD_REQUEST.toString());
            responseMap.put("errorMsg", "禁止非法获取信息");
            requestContext.setResponseBody(JSON.toJSONString(responseMap));
        }
        return null;
    }
}
